<template>
  <!-- 导入表 -->
  <el-dialog
    title="导入"
    :model-value="baTable.form.operate && baTable.form.operate === 'upload'"
    width="500px"
    append-to-body
    @close="baTable.toggleForm"
  >
    <el-upload
      ref="uploadRef"
      :limit="1"
      accept=".xlsx, .xls"
      :headers="state.upload.headers"
      :action="state.upload.url"
      :disabled="state.upload.isUploading"
      :on-change="changUpload"
      :on-remove="handleRemove"
      :http-request="uploadHttpRequest"
      :auto-upload="false"
      :multiple="false"
      drag
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <!-- <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="state.upload.updateSupport" />
          是否更新已经存在的设备数据
        </div> -->
        <span>仅允许导入xls、xlsx格式文件，且不超过10M</span>
        <el-link
          type="primary"
          :underline="false"
          style="font-size: 12px; vertical-align: baseline"
          @click="importTemplate"
          >下载模板</el-link
        >
      </template>
    </el-upload>
    <template #footer>
      <!-- <div slot="footer" class="dialog-footer"> -->
      <el-button @click="baTable.toggleForm('')">取 消</el-button>
      <el-button type="primary" @click="submitFileForm(uploadRef)"
        >确 定</el-button
      >
      <!-- </div> -->
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import {
  onMounted,
  onBeforeMount,
  onUnmounted,
  reactive,
  ref,
  inject,
} from "vue";
import type {
  UploadInstance,
  UploadProps,
  UploadRawFile,
  UploadFile,
  UploadFiles,
  UploadUserFile,
  UploadRequestOptions,
} from "element-plus";
import { ElNotification } from "element-plus"; //处理导航信息
import useCurrentInstance from "@/utils/useCurrentInstance";
import { _download, getToken, _upload } from "@/utils/axios";
import type baTableClass from "@/utils/baTable";
import { UploadFilled } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useAccess } from "@/store/backend/DeviceM/access";

const access = useAccess();

const uploadRef = ref<UploadInstance>();
const { proxy } = useCurrentInstance(); //mitt
const baTable = inject("baTable") as baTableClass;
const bomP = inject("bomP") as any;

const state: {
  upload: anyObj;
} = reactive({
  upload: {
    // 是否显示弹出层（设备导入）
    open: false,
    // 弹出层标题（设备导入）
    title: "",
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的设备数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: {
      Authorization: getToken(),
    },
    // !上传的地址待定
    url: "http://47.103.39.74:58088" + "/system/process/import",
  },
});

// interface Props {
//   modelValue: boolean;
// }
// const props = withDefaults(defineProps<Props>(), {
//   modelValue: false,
// });

// const emits = defineEmits<{
//   (e: "update:modelValue", value: boolean): void;
// }>();

// const closeForm = () => {
//   emits("update:modelValue", false);
// };

const handleFileUploadProgress = (event: any, file: any, fileList: any) => {
  state.upload.isUploading = true;
};
const handleFileSuccess = (response: any, file: any, fileList: any) => {
  state.upload.open = false;
  state.upload.isUploading = false;
  uploadRef.value!.clearFiles();
  //待重新获取表格数据
  baTable.onTableHeaderAction("refresh", {});
};

// 设备文件
const fileList = ref<UploadUserFile[]>([]);
const realUploadFile = ref<UploadUserFile[]>([]);

// 判断上传文件的类型，文件大小等
const changUpload: UploadProps["onChange"] = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log("文件限制", uploadFile, uploadFiles);
  const { uid, name, size } = uploadFile;
  //   文件类型限制
  const fileTypeFlag = /^.xls|.xlsx$/.test(
    name.substring(name.lastIndexOf(".")).toLowerCase()
  );
  if (!fileTypeFlag) {
    ElNotification({
      type: "warning",
      message: "文件类型只能是.png|.jpg|.jpeg",
    });
    const selectFileList = fileList.value.filter((item) => {
      return item.uid != uid;
    });
    fileList.value = selectFileList;
    return;
  }
  //文件大小进行校验
  if ((size as number) > 1024 * 1024 * 5) {
    ElNotification({
      type: "warning",
      message: "文件大小不能超过10Mb",
    });
    const selectFileList = fileList.value.filter((item) => {
      return item.uid != uid;
    });
    fileList.value = selectFileList;
    return;
  }
  //将上传的文件信息存入列表
  fileList.value.push(uploadFile);
  realUploadFile.value = [];
};

//移除文件
const handleRemove: UploadProps["onRemove"] = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log(uploadFile, uploadFiles);
  const { uid } = uploadFile;
  const selectFileList = fileList.value.filter((item) => {
    return item.uid != uid;
  });
  fileList.value = selectFileList;
};

const importTemplate = () => {
  _download(
    "/system/process/importTemplate",
    {},
    `process_template_${new Date().getTime()}.xlsx`
  );
};

const ceshi = () => {
  _download(
    "/system/user/export",
    {
      pageNum: 1,
      pageSize: 10,
      userName: undefined,
      phonenumber: undefined,
      status: undefined,
      deptId: undefined,
    },
    `user_${new Date().getTime()}.xlsx`
  );
};
//上传文件
const submitFileForm = (formEl: UploadInstance | undefined) => {
  console.log("成功!", state.upload);
  uploadRef.value!.submit(); // 点击上传：手动上传到服务器，此时会触发组件的http-request
  baTable.toggleForm("");
};

//手动上传
const uploadHttpRequest = (options: UploadRequestOptions) => {
  realUploadFile.value.push(options.file);
  let formData = new FormData(); //FormData对象，添加参数只能通过append('key', value)的形式添加
  formData.append("file", options.file); //添加文件对象
  bomP.importExcel(formData).then((res: any) => {
    baTable.onTableHeaderAction("refresh", {});
  });
};

const visible = () => {};
onMounted(() => {});
</script>
<style lang="scss" scoped></style>
